﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace MBEditor
{
    sealed class EditorUtils
    {
        static public string TrimAndRemoveLowererFirstWord(ref string line)
        {
            line = line.Trim();
            int spaceIndex = line.IndexOf(' ');
            if (spaceIndex == -1) spaceIndex = line.Length;
            string firstWord = line.Substring(0, spaceIndex).ToLower();
            line = line.Remove(0, firstWord.Length);
            line = line.Trim();
            return firstWord;
        }

        static public string CombineLinesToString(SortedDictionary<int, string> lines)
        {
            StringWriter buffer = new StringWriter();
            foreach (KeyValuePair<int, string> line in lines)
            {
                buffer.Write(line.Key);
                buffer.Write(" " + line.Value + '\r');
            }
            return buffer.ToString();
        }

        /// <summary>
        /// Function is necessary as the normal Encoding.GetBytes() methods,
        /// no matter the encoding, will try and preserve any extended ASCII
        /// chars as themselves. For instance 0xC4 is the - line drawing char in 
        /// code page 850 (which minibasic files are saved in), but in unicode 
        /// 0xC4 is the Ä char, which the Encoding.GetBytes methods try and preserve.
        /// So after Console.OutputEncoding.GetBytes() is called any 0xC4 chars are remapped
        /// to 0x8E which is the value of Ä in the 850 code page.
        /// </summary>
        /// <param name="str">string to convert</param>
        /// <returns>byte array with nulls removed</returns>
        static public byte[] StringTo850ByteArray(string str)
        {
            // all we're doing is lopping off the null bytes
            byte[] c = Encoding.Unicode.GetBytes(str);
            byte[] noNulls = new byte[c.Length / 2];
            
            for(int i = 0; i < c.Length; i += 2)
            {
                noNulls[i / 2] = (byte)c[i];
            }
            return noNulls;
        }

        public class ConWindow : IWin32Window
        {
            public ConWindow(IntPtr hwnd)
            {
                Handle = hwnd;
            }

            public IntPtr Handle
            {
	            get;
                private set;
            }
        }

        public static IWin32Window GetConsoleWindow()
        {
            IntPtr hwnd = Win32Funcs.GetConsoleWindow();
            return new ConWindow(hwnd);
        }
    }
}
